import type { Canceler, InternalAxiosRequestConfig } from 'axios'
import axios from 'axios'
import qs from 'qs'

const pendingRequest = new Map<string, Canceler>()

// 生成唯一key
const generateReqKey = (config: InternalAxiosRequestConfig) => {
  const { method, url, params, data } = config
  return [method, url, qs.stringify(params), qs.stringify(data)].join('&')
}

// 添加请求队列
export const addPendingRequest = (config: InternalAxiosRequestConfig) => {
  const requestKey = generateReqKey(config)
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken((cancel) => {
      if (!pendingRequest.has(requestKey)) {
        pendingRequest.set(requestKey, cancel)
      }
    })
}

export const removePendingRequest = (config: InternalAxiosRequestConfig) => {
  const requestKey = generateReqKey(config)
  if (pendingRequest.has(requestKey)) {
    const cancelToken = pendingRequest.get(requestKey)
    cancelToken && cancelToken(requestKey)
    pendingRequest.delete(requestKey)
  }
}
